import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Table,
  Tree,
  Input,
  Select,
  Button,
  Icon,
  Pagination,
  Modal,
  Switch,
  message,
  Form,
  Radio,
} from 'antd';
import styles from './index.css';
import { Dispatch, AnyAction } from 'redux';
import { produce, Draft } from 'immer';
import { userStatus } from '@/services/systemDevice';
import { FormComponentProps } from 'antd/es/form';
import {
  addUser,
  deleteUser,
  resetUserPwd,
  updateSysUser,
  userList,
  deptListSelect,
} from '@/services/systemDevice';
import { isMenuVisible } from './../../../utils/utils';
import _ from 'lodash';
import md5 from 'js-md5';
import { router } from 'umi';
const { TreeNode } = Tree;
const { Option } = Select;
const { TextArea } = Input;

interface userPsops extends FormComponentProps {
  dispatch: Dispatch<AnyAction>;
  // userList?: DeviceListsItem;
  loading: boolean;
  form: FormComponentProps['form'];
}
interface userManage {
  pageTotal: number;
  filterQueryParams: any;
  userStatus: any;
  params: any;
  showModel: boolean;
  userId: any;
  titles: any;
  isTrue: boolean;
  // value: any;
  reset: boolean;
  isAdd: boolean;
  isChecked: boolean;
  addChecked: boolean;
  userList: any;
  isCz: boolean;
  deptListUser: any;
  deptParams: any;
}
// @connect(({ loading, systemDevice }: any) => ({
//     loading: loading.effects['systemDevice/userList'],
//     userList: systemDevice.userList,
//     treeData: systemDevice.applyDeviceTreeData
// }))

class userManager extends Component<userPsops, userManage> {
  state: userManage = {
    pageTotal: 0,
    filterQueryParams: {
      pageNum: 1,
      pageSize: 10, //DEFAULT_PAGE_SIZE
      surLoginName: '',
      surPhoneNumber: '',
      surStatus: '',
    },
    params: {
      dictType: 'sys_user_status',
    },
    showModel: false,
    userId: [],
    titles: '',
    isTrue: false,
    reset: false,
    isAdd: true,
    isChecked: true,
    addChecked: true,
    userList: {},
    isCz: false,
    deptListUser: [],
    deptParams: {
      sdtStatus: '0',
    },
  };
  async componentWillMount() {
    // const { dispatch } = this.props;
    const [err, data] = await userStatus(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.userStatus = data;
        }),
      );
    }
    this.queryDept();
    // if (isMenuVisible('61')) {
      isMenuVisible('system:user:list') && this.handleFilterQuery();
    // }
  }
  componentWillReceiveProps(next: any) {
    // tab切换时间不一致时再次调用查询接口
    if (next.isUpdate !== this.props.isUpdate) {
      isMenuVisible('system:user:list') && this.handleFilterQuery();
    }
  }
  queryDept = async () => {
    //部门查询
    const [err, data] = await deptListSelect(this.state.deptParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.deptListUser = data;
        }),
      );
    }
  };
  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 登录名
    e.persist();
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.surLoginName = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  handleInputDrugNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 手机号
    e.persist();
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.surPhoneNumber = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  handleChangeSex = (e: string) => {
    console.log();
  };
  handleChangeStatus = (e: string) => {
    // 用户状态
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.surStatus = e;
      }),
    );
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    localStorage.setItem('userManagePage', pageNum);
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => isMenuVisible('system:user:list') && this.handleFilterQuery(),
    );
  };
  handleFilterQuery = async () => {
    // 搜索
    this.setState(
      produce((draft: Draft<dictManage>): void => {
        draft.filterQueryParams.pageNum =
          +localStorage.getItem('userManagePage') > 1 ? +localStorage.getItem('userManagePage') : 1;
      }),
    );
    const [err, data] = await userList(this.state.filterQueryParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.userList = data;
        }),
      );
    }
  };
  onSelect = (selectedKeys: any, info: any) => {
    console.log('selected', selectedKeys, info);
  };
  handleSure = async () => {
    //删除
    const [err, data] = await deleteUser({ ids: this.state.userId });
    if (!err) {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.isTrue = false;
        }),
      );
      message.info('删除成功');
    } else {
      this.setState(
        produce((draft: Draft<userManage>): void => {
          draft.isTrue = false;
        }),
      );
    }
    isMenuVisible('system:user:list') && this.handleFilterQuery();
  };
  handleSigDelete = (record: any) => {
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.userId = record.surUserId;
      }),
    );
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.titles = '确定要删除选中数据吗？';
        draft.isTrue = true;
      }),
    );
  };
  handleAddUser = () => {
    // 新增
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.showModel = true;
        draft.isAdd = true;
        draft.isCz = false;
      }),
    );
  };
  //修改
  handleEditor = (record: any) => {
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.isAdd = false;
        draft.isChecked = record.surStatus === '0' ? true : false;
        draft.showModel = true;
        draft.isCz = false;
      }),
    );
    setTimeout(() => {
      this.props.form.setFieldsValue({
        surUserId: record.surUserId,
        surUserName: record.surUserName,
        surPhoneNumber: record.surPhoneNumber,
        surEmail: record.surEmail,
        surLoginName: record.surLoginName,
        surPassword: record.surPassword,
        surSex: record.surSex == null ? '' : record.surSex,
        surStatus: record.surStatus == 0 ? true : false,
        surSystemKey: record.surSystemKey,
        surDeptId: record.surDeptId == null ? '' : record.surDeptId,
      });
    }, 0);
  };
  handleSubmit = (e: any) => {
    // 确认新增
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      values.surStatus = values.surStatus ? 0 : 1;
      values.surSystemKey = localStorage.getItem('surSystemKey');
      if (!err) {
        this.handleInsert(values);
      }
    });
  };
  handleInsert = async values => {
    // 确认插入(修改和新增)
    if (this.state.isAdd) {
      values.surPassword = md5(values.surPassword);
      // values.surSystemId = localStorage.getItem('surSystemId'),
      const [err, data] = await addUser(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<userManage>): void => {
            draft.showModel = false;
          }),
        );
        message.info('新增成功');
        this.props.form.resetFields();
      }
    } else {
      const [err, data] = await updateSysUser(values);
      if (!err) {
        this.setState(
          produce((draft: Draft<userManage>): void => {
            draft.showModel = false;
          }),
        );
        message.info('修改成功');
        this.props.form.resetFields();
      }
    }
    isMenuVisible('system:user:list') && this.handleFilterQuery();
  };
  resetPwd = async (record: any) => {
    //重置
    this.setState(
      produce((draft: Draft<userManage>): void => {
        draft.reset = true;
        draft.isCz = true;
      }),
    );
    this.props.form.setFieldsValue({
      surUserId: record.surUserId,
      surUserName: record.surUserName,
      surPhoneNumber: record.surPhoneNumber,
      surEmail: record.surEmail,
      surLoginName: record.surLoginName,
    });
  };
  handleReset = () => {
    //确认重置
    const params = {
      surUserId: '',
      password: '',
    };
    this.props.form.validateFields(async (error, values) => {
      params.surUserId = values.surUserId;
      params.password = md5(values.surPassword);
      if (!error) {
        const [err, data] = await resetUserPwd(params);
        if (!err) {
          this.setState(
            produce((draft: Draft<userManage>): void => {
              draft.reset = false;
            }),
          );
          message.info('重置密码成功');
        } else {
          this.setState(
            produce((draft: Draft<userManage>): void => {
              draft.reset = false;
            }),
          );
        }
      }
    });
    isMenuVisible('system:user:list') && this.handleFilterQuery();
  };
  onSwitchChange = (checked: any) => {
    // 切换选中状态
    this.setState({ isChecked: checked });
    this.setState({ addChecked: checked });
  };
  addFrom = () => {
    //新增、修改
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      wrapperCol: { span: 16 },
    };
    const title = this.state.isAdd ? '新增用户' : '编辑用户';
    return (
      <Modal
        title={title}
        visible={this.state.showModel}
        className="userModal_box"
        onCancel={() => {
          this.props.form.resetFields();
          this.setState({ showModel: false, addChecked: true });
        }}
      >
        <Form className="ant-advanced-search-form">
          <Form.Item {...formItemLayout} label="用户id:" style={{ display: 'none' }}>
            {getFieldDecorator('surUserId', {
              rules: [{ required: false, message: '请输入用户id' }],
            })(<Input type="text" placeholder="请输入用id" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="用户名称">
            {getFieldDecorator('surUserName', {
              rules: [
                { required: true, message: '请输入用户名' },
                {
                  max: 20,
                  message: '最多输入20位中文名',
                },
              ],
            })(<Input type="text" placeholder="请输入用户名" maxLength={20} />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="手机号码">
            {getFieldDecorator('surPhoneNumber', {
              rules: [
                {
                  required: true,
                  pattern: /^18[0-9]\d{8}$/,
                  message: '请输入正确的手机号',
                },
              ],
            })(<Input placeholder="请输入手机号" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="邮箱">
            {getFieldDecorator('surEmail', {
              rules: [
                {
                  required: true,
                  pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                  message: '邮箱输入不正确',
                },
              ],
            })(<Input placeholder="请输入邮箱" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="账号">
            {getFieldDecorator('surLoginName', {
              rules: [
                { required: true, message: '请输入账号' },
                {
                  max: 30,
                  message: '最多输入30位字符',
                },
              ],
            })(<Input placeholder="请输入账号" maxLength={30} />)}
          </Form.Item>
          {this.state.isAdd ? (
            <Form.Item {...formItemLayout} label="系统Id:" style={{ display: 'none' }}>
              {getFieldDecorator('surSystemId', {
                initialValue: localStorage.getItem('surSystemId'),
                rules: [{ required: false }],
              })(<Input placeholder="请输入系统Id" />)}
            </Form.Item>
          ) : null}
          {this.state.isAdd ? (
            <Form.Item {...formItemLayout} label="登录密码:">
              {getFieldDecorator('surPassword', {
                rules: [{ required: true, message: '请输入登录密码' }],
              })(<Input placeholder="请输入登录密码" />)}
            </Form.Item>
          ) : null}
          <Form.Item {...formItemLayout} label="用户性别">
            {getFieldDecorator('surSex', {
              initialValue: '',
              rules: [{ required: false, message: '请选择用户性别' }],
            })(
              <Select style={{ width: 200 }}>
                <Option value="">请选择</Option>
                <Option value="0">男</Option>
                <Option value="1">女</Option>
              </Select>,
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="部门">
            {getFieldDecorator('surDeptId', {
              initialValue: '',
              rules: [{ required: true, message: '请选择部门' }],
            })(
              <Select style={{ width: 200 }}>
                <Option value="">请选择</Option>
                {_.map(this.state.deptListUser, (item: any, index: number) => (
                  <Option key={index} value={item.sdtDeptId}>
                    {item.sdtDeptName}
                  </Option>
                ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="用户状态:">
            {getFieldDecorator('surStatus', {
              initialValue: true,
              rules: [{ required: false }],
            })(
              <Switch
                defaultChecked={true}
                checked={this.state.isAdd ? this.state.addChecked : this.state.isChecked}
                onChange={this.onSwitchChange}
              />,
            )}
          </Form.Item>
        </Form>
        <div className={styles.footBtnArea}>
          <div
            style={{ marginRight: '30px' }}
            className={styles.foot_btn}
            onClick={this.handleSubmit}
          >
            确定
          </div>
          <div
            className={styles.foot_btn}
            onClick={() => {
              this.setState({ showModel: false, addChecked: true });
              this.props.form.resetFields();
            }}
          >
            取消
          </div>
        </div>
      </Modal>
    );
  };
  resetFrom = () => {
    //重置
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      wrapperCol: { span: 16 },
    };
    return (
      <Modal
        title="重置密码"
        className="userModal_box reset-box"
        visible={this.state.reset}
        onCancel={() => {
          this.props.form.resetFields();
          this.setState({ reset: false });
        }}
      >
        <Form>
          <Form.Item {...formItemLayout} label="用户id:" style={{ display: 'none' }}>
            {getFieldDecorator('surUserId', {
              rules: [{ required: false, message: '请输入用户id' }],
            })(<Input type="text" placeholder="请输入用id" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="账号:">
            {getFieldDecorator('surLoginName', {
              rules: [{ required: true, message: '请输入账号' }],
            })(<Input placeholder="请输入账号" disabled={true} />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="登录密码:">
            {getFieldDecorator('surPassword', {
              rules: [{ required: true, message: '请输入登录密码' }],
            })(<Input placeholder="请输入登录密码" />)}
          </Form.Item>
        </Form>
        <div className={styles.footBtn}>
          <div
            style={{ marginRight: '30px' }}
            className={styles.foot_btn}
            onClick={this.handleReset}
          >
            确定
          </div>
          <div
            className={styles.foot_btn}
            onClick={() => {
              this.setState({ reset: false });
              this.props.form.resetFields();
            }}
          >
            取消
          </div>
        </div>
      </Modal>
    );
  };
  columns: any = [
    {
      title: '用户编号',
      dataIndex: 'surUserId',
      key: 'surUserId',
    },
    {
      title: '账号',
      dataIndex: 'surLoginName',
      key: 'surLoginName',
    },
    {
      title: '用户名称',
      dataIndex: 'surUserName',
      key: 'surUserName',
    },
    // {
    //     title: '部门',
    //     dataIndex: 'dept.sdtDeptName',
    //     key: 'dept.sdtDeptName',
    // },
    {
      title: '手机',
      dataIndex: 'surPhoneNumber',
      key: 'surPhoneNumber',
    },
    {
      title: '用户状态',
      dataIndex: 'operateName',
      key: 'operateName',
      render: (text: any, record: any) => {
        return record.surStatus == 0 ? (
          <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
        ) : (
          <span style={{ color: '#cb3203' }}>停用</span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'surCreateTime',
      key: 'surCreateTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text: any, record: any) => {
        return (
          <span className={styles.one}>
            {isMenuVisible('system:user:update') && (
              <a
                onClick={() => {
                  this.handleEditor(record);
                }}
              >
                编辑
              </a>
            )}
            {isMenuVisible('system:user:remove') && (
              <a
                onClick={() => {
                  this.handleSigDelete(record);
                }}
              >
                删除
              </a>
            )}
            {isMenuVisible('system:user:resetPwd') && (
              <a
                onClick={() => {
                  this.resetPwd(record);
                }}
              >
                重置密码
              </a>
            )}
            {isMenuVisible('system:user:allocatedList') && (
              <a
                onClick={() => {
                  router.push(`/system/role/${record.surUserId}`);
                }}
              >
                分配角色
              </a>
            )}
          </span>
        );
      },
    },
  ];
  render() {
    const { userStatus } = this.state;
    return (
      <div className={styles.container}>
        <div className={styles.userRight}>
          <div className={styles['inforAnasy-container-top-btn']}>
            {isMenuVisible('system:user:insert') && (
              <Button type="link" onClick={this.handleAddUser}>
                <Icon type="plus" />
                新增
              </Button>
            )}
          </div>
          <div style={{ overflow: 'hidden' }}>
            <div>
              <div className={styles['dev-search-select']}>
                <Input
                  value={this.state.filterQueryParams.surLoginName}
                  placeholder="请输入账号"
                  onChange={this.handleChange}
                  addonBefore="账号"
                  type="text"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <Input
                  value={this.state.filterQueryParams.surPhoneNumber}
                  placeholder="请输入手机号"
                  onChange={this.handleInputDrugNameChange}
                  addonBefore="手机号"
                  type="number"
                />
              </div>
              <div className={styles['dev-search-select']}>
                <span className={styles['dev-search-select-title']}>用户状态</span>
                <Select
                  // placeholder="请选择"
                  // defaultValue="请选择"
                  placeholder="请选择"
                  style={{ width: 200 }}
                  onChange={this.handleChangeStatus}
                  value={this.state.filterQueryParams.surStatus}
                >
                  {/* <Option value="">请选择</Option> */}
                  {_.map(userStatus, (item: any, index: number) => (
                    <Option key={index} value={item.dictValue}>
                      {item.dictLabel}
                    </Option>
                  ))}
                </Select>
              </div>
              {isMenuVisible('system:user:list') && (
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams.pageNum = 1;
                      }),
                      () => {
                        this.handleFilterQuery();
                      },
                    );
                  }}
                >
                  搜索
                </Button>
              )}

              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.surLoginName = '';
                      draft.filterQueryParams.surPhoneNumber = '';
                      draft.filterQueryParams.surStatus = '';
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <Table
            scroll={{ y: '500px' }}
            pagination={false}
            columns={this.columns}
            dataSource={this.state.userList.rows}
            rowKey="surUserId"
          />
          <div className="pagination-box">
            <Pagination
              defaultCurrent={this.state.filterQueryParams.pageNum}
              current={this.state.filterQueryParams.pageNum}
              onChange={this.handlePageChange}
              total={this.state.userList.total ? this.state.userList.total : 0}
            />
            <span className="pagination-title-box">
              第{this.state.filterQueryParams.pageNum}/
              {Math.ceil(
                (this.state.userList.total ? this.state.userList.total : 0) /
                  this.state.filterQueryParams.pageSize,
              )}
              页 共{this.state.userList.total ? this.state.userList.total : 0}条
            </span>
          </div>
          {!this.state.isCz ? this.addFrom() : this.resetFrom()}
          <Modal
            title="系统提示"
            className={styles.modal}
            visible={this.state.isTrue}
            onCancel={() => {
              this.setState({ showModel: false });
            }}
          >
            <div className={styles.titles}>{this.state.titles}</div>
            <div className={styles.footBtn}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSure}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ isTrue: false });
                }}
              >
                取消
              </div>
            </div>
          </Modal>
        </div>
      </div>
    );
  }
}
export default Form.create<userPsops>()(userManager);
